<?php

namespace App\Models;

use App\Utils\SSUtil;


//use Bican\Roles\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract;
//use Bican\Roles\Models\Role;
//use Bican\Roles\Traits\HasRoleAndPermission;
use DB;
use Exception;
use Illuminate\Http\Request;
use ReflectionClass;

/**
 * 管理员模型类
 */
class Admin extends BaseModel
{

    public $table = "admins";    //指定表名
    public $allPer = array();    //此用户权限列表

    //表关系区===========================================================================

    /**
     * 角色对象
     */
    public function roles()
    {
        return $this->hasOne(MRoles::class, "id", "role_id");
    }

    /**
     * 角色对象
     */
    public function permission_role()
    {
        return $this->hasOne(MPermissionRoles::class, "role_id", "role_id");
    }

    //数据逻辑区===========================================================================

    /**
     * 记录管理员的登录状态
     * $bool = true 记住登录状态
     * $bool = false 退出登录装态
     */
    public function loginStatus($bool = true)
    {
        if ($bool) {
            ss([
                "admin_id" => $this->id,
                "admin_name" => $this->username,
                "admin_super" => $this->super,
                "admin_role" => $this->role_id,
            ]);
        } else {
            SSUtil::forget(['admin_id', 'admin_name', 'admin_super', 'admin_role']);
        }
        return $this;
    }

    /**
     * 管理员登录验证
     */
    public static function loginValid(Request $request)
    {
        $admin = Admin::where('username', strtolower($request->username))
            ->where('userpass', md5($request->userpass))->first();
        if (empty($admin)) {
            return null;
        }
        return $admin;
    }

    /**
     * 存储当前登录的IP和时间
     */
    public function refreshIP(Request $request)
    {
        $this->lastip = $request->getClientIp();
        $this->lasttime = time();
        return $this->save();
    }

    /**
     * 编辑或保存新的管理员
     * @param Request $request
     * @return bool
     */
    public function createOrSave_api($request)
    {
        $this->username = strtolower($request->name);
        $this->userpass = md5($request->pass);
        $this->role_id = $request->role_id;
        return $this->save();
    }

    /**
     * 检查是否存在同名的账号
     *
     * return true 存在 false 不存在
     */
    public function existUserName($username)
    {
        if (Admin::where('username', strtolower($username))->count() != 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查当前管理员是否有某项权限
     * @param $permissions 数组 或 单个权限slug
     * @return bool 只要包含一个权限，返回真
     */
    public function rolesCan($permissions)
    {
        if ($this->super == 1) {    //超级管理员拥有所有权限
            return true;
        }

        //当前管理员的所有权限
        if (empty($this->allPer)) {
            $this->allPer = unserialize($this->permission_role->permissions);
        }

        //检测权限
        foreach ($this->allPer as $per) {
            if (is_array($permissions)) {
                foreach ($permissions as $item) {
                    if ($per == $item) {
                        return true;
                    }
                }
            } else {
                if ($per == $permissions) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 判断角色是否存在
     * 存在 true   不存在 false
     */
    public static function existRoles(Request $request)
    {
        $role = MRoles::where('name', $request->name)->first();
        if (empty($role)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 判断角色下是否还有管理员是否存在
     * 存在 true   不存在 false
     */
    public static function rolesHasManager($request)
    {
        $id_list = json_decode($request->id, true);
        $result = MRoles::find($id_list);
        $admins = Admin::all();
        foreach ($result as $value) {
            $id = $value->id;
            foreach ($admins as $admin) {
                if ($admin->role_id == $id) {
                    return true;
                } else {
                    return false;
                }
            }
        }

    }


    //数据验证区===========================================================================

    /**
     * 管理员登录数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function loginRulesWithMsg($flag)
    {
        $rules = array(
            "username" => "required|alpha|between:3,50",
//            'userpass' => array('Regex:/^(^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{10,}$)/'),
            'yzm' => 'required|numeric',
        );

        $msg = array(
            "username.required" => "请填写用户名",
            "username.alpha" => "用户名只能为纯字母",
            "username.between" => "用户名只能3-50位之间",
//            "userpass.regex" => "密码必须包含大小写字母、数字与特殊符号"
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 管理员登录数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function saveRulesWithMsg($flag)
    {
        $rules = array(
            "username" => "required|alpha|between:3,50",
            'userpass' => array('Regex:/^(^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{10,}$)/'),
            'roles' => 'required|numeric',
        );

        $msg = array(
            "username.required" => "请填写用户名!",
            "username.alpha" => "用户名只能为纯字母!",
            "username.between" => "用户名只能3-50位之间!",
            "userpass.regex" => "密码必须包含大小写字母、数字与特殊符号!",
            "roles.required" => "必须选择管理员角色!"
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 管理员登录数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function adminsSaveRulesWithMsg($flag)
    {
        $rules = [
            "name" => "required|alpha|between:3,50",
            'pass' => array('Regex:/^(^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{10,}$)/'),
            'role_id' => 'required|numeric',
        ];

        $msg = [
            "name.required" => "请填写用户名!",
            "name.alpha" => "用户名只能为纯字母!",
            "name.between" => "用户名只能3-50位之间!",
            "pass.regex" => "密码必须包含大小写字母、数字与特殊符号!",
            "role_id.required" => "必须选择管理员角色!"
        ];

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 一键初始化请求参数验证
     * $flag 0 = rules  1 = msg
     */
    public static function initialRulesWithMsg($flag)
    {
        $rules = array(
            'username' => 'required|alpha|between:3,50',
            'userpass' => 'required|max:30',
            'adminpass' => 'required'
        );

        $msg = array(
            "username.alpha" => "用户名只能为纯字母组成",
            "username.between" => "用户名只能3-50位之间",
            "userpass.required" => "请填写根节点登录密码！",
            "adminpass.required" => "请填写管理员密码！",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 自动测试数据效验
     * $flag 0 = rules  1 = msg
     */
    public static function testRulesWithMsg($flag)
    {
        $rules = array(
            "user_num" => 'required|numeric|between:1,9999999',
            'admin_pass' => 'required|between:3,50',
        );

        $msg = array(
            "user_num.required" => "请填写要注册的用户数量！",
            "user_num.between" => "请填写合法的会员数量！",
            "admin_pass.required" => "管理员密码必须验证！"
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

}